/*
 * This file is part of ELCube.
 *
 * ELCube is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * ELCube is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with ELCube.  If not, see <https://www.gnu.org/licenses/>.
 */
package cn.nkpro.elcube.security.validate2;

import cn.nkpro.elcube.platform.gen.UserAccountSecret;
import cn.nkpro.elcube.security.UserAccountService;
import cn.nkpro.elcube.security.bo.UserDetails;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.core.annotation.Order;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.security.cert.X509Certificate;

/**
 * 1、使用微信code获取token
 */
@ConditionalOnProperty({
        "nk.wxmp.app-id",
        "nk.wxmp.app-secret"
})
@Component
@Slf4j
@Order(2003)
public class NkLoginWxmpAuthenticationFilter extends GenericFilterBean implements AuthenticationFilterV2 {

    @Value("${nk.wxmp.app-id}")
    private String appId;
    @Value("${nk.wxmp.app-secret}")
    private String appSecert;

    @Autowired
    private AuthenticationUtils authenticationUtils;
    @Autowired
    private UserAccountService accountService;


    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {

        if (request instanceof HttpServletRequest && response instanceof HttpServletResponse) {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            if (authentication == null || !authentication.isAuthenticated()) {

                // 区分客户端
                String client    = authenticationUtils.obtainParam(request, "elcube-client");
                // 微信的code
                String code      = authenticationUtils.obtainParam(request, "elcube-wxmp-code");

                if (StringUtils.isNoneBlank(client, code)) {

                    try {
                        String openId = getOpenId(code);

                        UserAccountSecret accountSecret = accountService.getAccountSecretByCode("wxmp", openId);
                        if(accountSecret==null){
                            throw new BadCredentialsException("code不存在");
                        }

                        UserDetails details = accountService.loadUserById(accountSecret.getAccountId());
                        AuthenticationUtils.simpleValidate(details);

                        AbstractAuthenticationToken auth = new UsernamePasswordAuthenticationToken(details.getUsername(),null, details.getAuthorities());
                        auth.setDetails(details);

                        ((HttpServletResponse)response).setStatus(HttpServletResponse.SC_OK);
                        response.setCharacterEncoding("utf-8");
                        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
                        PrintWriter printWriter = response.getWriter();
                        printWriter.print(authenticationUtils.grantToken(client, details.getUsername()));
                        printWriter.flush();
                        printWriter.close();
                    }catch (AuthenticationException e){
                        authenticationUtils.commence((HttpServletResponse)response, e);
                        return;
                    }
                }
            }
        }

        filterChain.doFilter(request, response);
    }

    private String getOpenId(String code) {

        JSONObject jsonObject;
        try (CloseableHttpClient client = getClient()) {
            HttpGet get = new HttpGet(
                    String.format(
                            "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code",
                            appId,
                            appSecert,
                            code
                    )
            );
            HttpResponse execute = client.execute(get);
            jsonObject = JSON.parseObject(EntityUtils.toString(execute.getEntity()));
        } catch (Exception e) {
            throw new AuthenticationServiceException(e.getMessage());
        }

        if(jsonObject.containsKey("openid")&&StringUtils.isNotBlank(jsonObject.getString("openid"))){
            return jsonObject.getString("openid");
        }
        throw new AuthenticationServiceException(StringUtils.defaultIfBlank(jsonObject.getString("errmsg"),"微信小程序登录错误"));
    }

    private static CloseableHttpClient getClient() {
        try {
            SSLContext ctx = SSLContext.getInstance("TLS");
            X509TrustManager tm = new X509TrustManager() {
                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
                @Override
                public void checkClientTrusted(X509Certificate[] arg0,String arg1) {
                }
                @Override
                public void checkServerTrusted(X509Certificate[] arg0,String arg1) {
                }
            };
            ctx.init(null, new TrustManager[] { tm }, null);
            SSLConnectionSocketFactory ssf = new SSLConnectionSocketFactory(
                    ctx, NoopHostnameVerifier.INSTANCE);
            return HttpClients.custom()
                    .setSSLSocketFactory(ssf).build();
        } catch (Exception e) {
            return HttpClients.createDefault();
        }
    }
}
